package pl.un4giv3n.mightvsmagic.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia 
 * change user password
 */
public class ChangePasswordAction extends ProfilePageAction {

	private static final long serialVersionUID = 1L;

	/**
	 * old passwd
	 */
	private String oldPassword;
	/**
	 * user new passwd
	 */
	private String newPassword;
	/**
	 * retyped passwd to check misspelling
	 */
	private String newRetyped;

	/**
	 * logged in user
	 */
	private User user;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if(user == null){
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		newPassword = newPassword.trim();
		oldPassword = UserUtil.encyptPassword(oldPassword.trim());
		if (validateData()) {
			entityManager.getTransaction().begin();
			newPassword = UserUtil.encyptPassword(newPassword);
			user.setPassword(newPassword);
			entityManager.merge(user);
			entityManager.flush();
			entityManager.getTransaction().commit();
			entityManager.close();
			if(user.getUserType() == UserType.ADMIN){
				return ADMIN_PAGE;
			}
			return SUCCESS;
		} else {
			entityManager.close();
			return INPUT;
		}
	}

	/**
	 * @param entityManager 
	 * @return true if password can be changed
	 */
	private boolean validateData() {
		boolean valid = true;
		if(!oldPassword.equals(user.getPassword())){
			valid = false;
			addActionError("Niepoprawne stare hasło");
		}
		if (!UserUtil.validatePassword(newPassword)) {
			valid = false;
			addActionError("Hasło musi zawierać conajmniej 6 znaków, w tym conajmniej jedną dużą i małą literę oraz cyfrę. Dozwolone są znaki alfanumeryczne i _");
		} else if (!newPassword.equals(newRetyped)) {
			valid = false;
			addActionError("Hasła nie zgadzają się");
		}
		return valid;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getNewRetyped() {
		return newRetyped;
	}

	public void setNewRetyped(String newRetyped) {
		this.newRetyped = newRetyped;
	}

}
